//
//  LYPublicPictureVidowViewController.m
//  artist
//
//  Created by laotang on 16/4/9.
//  Copyright © 2016年 viviyoo. All rights reserved.
//

#import "LYPublicPictureViewController.h"

#import "LSYUIActionSheet.h"
#import <QBImagePickerController.h>
#import "LYPublicMethod.h"
#import <Masonry.h>
#import "LSYPhotoAddView.h"
#import "LYRequestTool.h"
#import "NSDate+Utils.h"
#import "QNUploadManager.h"
#import "QNUploadOption.h"
#import "LYSelectCircleViewController.h"
#define LSYSendPostLimitMaxImageCount 9
@interface LYPublicPictureViewController()<UITextViewDelegate>

@property(nonatomic, strong) UIView *editContentView;

@property(nonatomic, strong) UILabel *placeHoldLabel;
@property(nonatomic, strong) UILabel *countlabel;
@property(nonatomic, strong) UIView *placeHoldView;
@property(nonatomic, strong) UITextView *textView;
@property(nonatomic, strong) LSYPhotoAddView *addPhotoView;
@property(nonatomic, strong) UIButton *rightButton;

@property (strong, nonatomic) NSMutableArray *selectedImageList;
@property (nonatomic, assign) NSInteger uploadIndex; // 当前上传的图片下标
@property (nonatomic, strong) NSMutableString *imageLink;
@property (nonatomic, copy)  void(^uploadImageCompleteHandle)(NSString *);

@end

@implementation LYPublicPictureViewController

- (void)viewDidLoad{
    self.automaticallyAdjustsScrollViewInsets = NO;
    [super viewDidLoad];
    self.title = @"发布主题";
    [self setupSubView];
    [self setupConstraints];
    self.filterType = QBImagePickerControllerFilterTypePhotos;
    self.view.backgroundColor = [UIColor whiteColor];
    self.selectedImageList = [NSMutableArray array];
    self.choseBigImageLists = [NSMutableArray array];
    WS(weakSelf)

    [LYRequestTool acquirQiNiusuccess:^(NSString *token) {
        
        weakSelf.qiNiuToken = token;
    } failure:^(NSString *code, NSString *message) {
        
    }];

    UIBarButtonItem * rightitem = [[UIBarButtonItem alloc] initWithTitle:@"下一步" style:UIBarButtonItemStylePlain target:self action:@selector(publicData)];
    self.navigationItem.rightBarButtonItem = rightitem;

    

  }

#pragma mark 


- (void)setupSubView{
    
    [self.view addSubview:self.editContentView];
    [self.editContentView addSubview:self.textView];
    [self.editContentView addSubview:self.placeHoldLabel];
    [self.editContentView addSubview:self.countlabel];
    [self.view addSubview:self.placeHoldView];
    [self.view addSubview:self.addPhotoView];

    
}




- (void)setupConstraints{
    

    WS(weakSelf)
    
    [self.editContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(170);
    }];
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(weakSelf.editContentView);
        make.bottom.mas_equalTo(weakSelf.editContentView.mas_bottom).offset(- 20);
    }];

    [self.placeHoldLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(weakSelf.textView).offset(7);
    }];
    
    [self.countlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.mas_equalTo(weakSelf.editContentView);
    }];
    [self.placeHoldView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(weakSelf.editContentView.mas_bottom);
        make.height.mas_equalTo(6);

    }];
    [self.addPhotoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(weakSelf.placeHoldView.mas_bottom);
    }];
    [self.addPhotoView resetPhotoView];
}
- (UIView *)editContentView{
    if(!_editContentView){
        _editContentView = [[UIView alloc] init];
        
    }
    return _editContentView;
}
- (UILabel *)placeHoldLabel{
    
    if(!_placeHoldLabel){
        _placeHoldLabel = [UILabel creatLabelWithText:@"请输入内容" Font:[UIFont systemFontOfSize:15] textColor:LYColorWithHex(0x999999) textAlignment:NSTextAlignmentLeft];
    }
    return _placeHoldLabel;
}

- (UILabel *)countlabel{
    
    if(!_countlabel){
        
        _countlabel = [UILabel creatLabelWithText:@"0/1000" Font:[UIFont systemFontOfSize:10] textColor:LYColorWithHex(0x555555) textAlignment:NSTextAlignmentRight];
    }
    return _countlabel;
}

- (UITextView *)textView{
    
    if(!_textView){
        _textView = [[UITextView alloc] initWithFrame:CGRectZero];
        _textView.font = [UIFont systemFontOfSize:15];
        _textView.delegate = self;
    }
    return _textView;
}
- (UIView *)placeHoldView{
    if(!_placeHoldView){
        _placeHoldView = [[UIView alloc] init];
        _placeHoldView.backgroundColor = LYColorWithHex(0xd9d9d9);
    }
    return _placeHoldView;
}

- (LSYPhotoAddView *)addPhotoView{
    
    if(!_addPhotoView){
        _addPhotoView = [[LSYPhotoAddView alloc] init];
        WS(weakSelf)
        [_addPhotoView setAddButtonClickBlock:^{
            [weakSelf addPhotoButtonPressed];
        }];
        
        [_addPhotoView setDelButtonClickBlock:^(NSInteger index) {
           
            [weakSelf.choseBigImageLists removeObjectAtIndex:index];
            [weakSelf.addPhotoView resetPhotoView];
        }];
//        [_addPhotoView set]
    }
    return _addPhotoView;
}

#pragma mark - textViewDelegate



- (void)textViewDidChange:(UITextView *)textView{
    
    self.placeHoldLabel.hidden = textView.text.length;
    self.countlabel.text = [NSString stringWithFormat:@"%zd/1000", textView.text.length];

}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if(textView.text.length < 1000 || [text isEqualToString:@""]){
        return  YES;
    }else{
        return NO;
    }
}


#pragma mark - addPhoto


- (void)addPhotoButtonPressed
{
    NSArray *imagesArray = _selectedImageList;
    if (imagesArray.count >= 9) {
        [SVProgressHUD showErrorWithStatus:@"图片不能超过9张"];
        return;
    }
    
    LSYUIActionSheet* addPicActionSheet = [[LSYUIActionSheet alloc]initWithTitle:@"添加照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
    addPicActionSheet.tag = 1000;
    [addPicActionSheet showInNoErrorView:self.view];
}



-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag ==1000) {
        
        if (buttonIndex == 0) {
            //拍照
            if (![LYPublicMethod checkCameraAuthorizationStatus]) {
                return;
            }
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = NO;//设置可编辑
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];//进入照相界面
        }
        else if (buttonIndex == 1){
            //相册
            if (![LYPublicMethod checkPhotoLibraryAuthorizationStatus]) {
                return;
            }
            QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
            imagePickerController.filterType = self.filterType;
            imagePickerController.delegate = self;
            imagePickerController.allowsMultipleSelection = YES;
            imagePickerController.maximumNumberOfSelection = LSYSendPostLimitMaxImageCount - self.choseBigImageLists.count;
            [self presentViewController:imagePickerController animated:YES completion:NULL];
        }
    }
}


/**
 *  相册选择回调
 */
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets
{
    [self dealWithSelectAssets:assets];

}
- (BOOL)qb_imagePickerController:(QBImagePickerController *)imagePickerController shouldSelectAsset:(ALAsset *)asset
{
    NSMutableOrderedSet *orderSet = [imagePickerController selectedAssetURLs];
    NSInteger currentCount = (orderSet.count + self.choseBigImageLists.count);
    if (currentCount >= LSYSendPostLimitMaxImageCount) {
        [self showNoCanSelectImageAler];
        return NO;
    }
    return YES;
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {
    [self.choseBigImageLists addObject:image];
    self.addPhotoView.imageUrlArray = self.choseBigImageLists;
    [self resetPhotoViewByImageChange];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage] ;
    [self.choseBigImageLists addObject:image];
    self.addPhotoView.imageUrlArray = self.choseBigImageLists;
    [self resetPhotoViewByImageChange];
    
    [self dismissViewControllerAnimated:YES completion:nil];

}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];

}

- (UIImage *)fullResolutionImageFromALAsset:(ALAsset *)asset{
    ALAssetRepresentation *assetRep = [asset defaultRepresentation];
    CGImageRef imgRef = [assetRep fullResolutionImage];
    UIImage *img = [UIImage imageWithCGImage:imgRef scale:assetRep.scale orientation:(UIImageOrientation)assetRep.orientation];
    return img;
}

- (void)resetPhotoViewByImageChange
{
    UIImageView *image = [[UIImageView alloc]init];
    [image sd_setImageWithURL:nil placeholderImage:nil];
    
    [self.addPhotoView resetPhotoView];
}
- (void)dealWithSelectAssets:(NSArray *)assets{
    
    
    for (ALAsset *assetItem in assets) {
        UIImage *highQualityImage = [self fullResolutionImageFromALAsset:assetItem];
        [self.choseBigImageLists addObject:highQualityImage];
        
    }
    self.addPhotoView.imageUrlArray = self.choseBigImageLists;
    [self resetPhotoViewByImageChange];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)showNoCanSelectImageAler
{
    NSString *notice = [NSString stringWithFormat:@"最多可选%@张图片",[@(LSYSendPostLimitMaxImageCount)stringValue]];
    UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"提示" message:notice delegate:self cancelButtonTitle:@"知道啦!" otherButtonTitles:nil, nil];
    [aler show];
}

#pragma mark

- (void)publicData{
    
    WS(weakSelf)


    if (!self.textView.text.length){
        [SVProgressHUD showErrorWithStatus:@"请输入内容"];
        return ;
    }
    LYUserInfoModel *userInfo = [VVYSaveDataManager getDataWithKey:KEY_USERMESSAGE];
    
    if (!self.choseBigImageLists.count && userInfo.role_id != 1){
        [SVProgressHUD showErrorWithStatus:@"请选择图片"];
        return ;

    }
    [self setUploadImageCompleteHandle:^(NSString *imageLink) {
        

        
        NSString *images = nil;
        if(weakSelf.imageLink.length > 0){
            
            images = [weakSelf.imageLink substringToIndex:weakSelf.imageLink.length - 1];
            
        }
        [SVProgressHUD showSuccessWithStatus:@"上传图片成功"];
        LYSelectCircleViewController * selectedVC = [[LYSelectCircleViewController alloc] initWithContent:weakSelf.textView.text imagees:images];

        [weakSelf.navigationController pushViewController:selectedVC animated:YES];

        
    }];
    self.imageLink = [NSMutableString string];
    [self uploadImagesuccess:nil];
    [self.view endEditing:YES];

}

- (void)uploadImagesuccess:(void (^)(NSString * imageLink))success{

    if (self.uploadIndex == self.choseBigImageLists.count  ){
        return;
    }
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    
    UIImage *obj = self.choseBigImageLists[0];
    NSData *data = UIImageJPEGRepresentation(obj, 0.1);

    WS(weakSelf)
    QNUploadOption *option = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
        
        NSString *message = [NSString stringWithFormat:@"正在上传%zd/%zd张", weakSelf.uploadIndex + 1, weakSelf.choseBigImageLists.count];

        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD showProgress:percent status:message];
        
    }];
    
    [upManager putData:data key:nil token:self.qiNiuToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
            NSString *urlString= [NSString stringWithFormat:@"http://7xrlrd.com1.z0.glb.clouddn.com/%@",resp[@"key"]];
        [weakSelf.imageLink appendFormat:@"%@,",urlString];
        NSLog(@"%@",weakSelf.imageLink);
        if (weakSelf.uploadIndex + 1 >= weakSelf.choseBigImageLists.count){ // 最后一样
            if (weakSelf.uploadImageCompleteHandle){
                weakSelf.uploadImageCompleteHandle(weakSelf.imageLink);
            }
        }else{
            weakSelf.uploadIndex ++;
            [weakSelf uploadImagesuccess: nil];
        }
    } option:option];
    
}

@end
